package com.ai.controller;

import com.ai.service.VectorStoreService;
import com.ai.service.impl.DocumentParserService;
import com.ai.service.impl.DocumentSplitterService;
import com.ai.service.impl.MetadataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;

/**
 * 文档处理控制器
 * 文档解析，分割等
 */

@Slf4j
@RestController
@RequestMapping("/documents/v1")
public class DocumentController {

    private final DocumentParserService documentParserService;
    private final DocumentSplitterService documentSplitterService;
    private final VectorStoreService vectorStoreService;
    private final MetadataService metadataService;

    @Autowired
    public DocumentController(DocumentParserService documentParserService,
                              DocumentSplitterService documentSplitterService,
                              VectorStoreService vectorStoreService,
                              MetadataService metadataService) {
        this.documentParserService = documentParserService;
        this.documentSplitterService = documentSplitterService;
        this.vectorStoreService = vectorStoreService;
        this.metadataService = metadataService;
    }

    /**
     * 解析上传的文件，返回提取的文本内容
     * @param file 上传的文件
     * @return 提取的文本内容
     */
    @PostMapping("/parse")
    public ResponseEntity<String> parseDocument(@RequestParam("file") MultipartFile file) {
        try {
            String content = documentParserService.parseMultipartFile(file);
            return ResponseEntity.ok(content);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body("文件解析失败: " + e.getMessage());
        }
    }

    /**
     * 分割上传的文件内容
     * @param file 上传的文件
     * @return 分割后的文本块列表
     */
    @PostMapping("/split")
    public ResponseEntity<List<String>> splitDocument(@RequestParam("file") MultipartFile file) {
        try {
            //List<String> chunks = documentSplitterService.splitDocumentContent(file);
            List<String> chunks = documentSplitterService.customerSplitDocumentContent(file);
            return ResponseEntity.ok(chunks);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(List.of());
        }
    }

    /**
     * 提取上传文件的元数据
     * @param file 上传的文件
     * @return 元数据映射
     */
    @PostMapping("/metadata")
    public ResponseEntity<Map<String, Object>> extractMetadata(@RequestParam("file") MultipartFile file) {
        try {
            Map<String, Object> metadata = metadataService.extractMetadata(file);
            return ResponseEntity.ok(metadata);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of());
        }
    }

    /**
     * 相似性搜索 返回文档信息
     * @param query 查询文本
     * @param topK 返回最相似的结果数量（可选，默认为5）
     * @return 相似的文档列表
     */
    @GetMapping("/search")
    public ResponseEntity<List<Document>> searchDocuments(
            @RequestParam String query,
            @RequestParam(defaultValue = "5") int topK) {
        try {
            List<Document> results = vectorStoreService.similaritySearch(query, topK);
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            log.error("相似性搜索失败: {}" , e.getMessage(), e);
            return ResponseEntity.internalServerError().body(List.of());
        }
    }

    /**
     * 获取文件完整信息（内容预览 + 元数据）
     * @param file 上传的文件
     * @return 文件信息
     */
    @PostMapping("/info")
    public ResponseEntity<String> getFileInfo(@RequestParam("file") MultipartFile file) {
        try {
            String info = metadataService.getFileInfoWithMetadata(file);
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body("获取文件信息失败: " + e.getMessage());
        }
    }

}